/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author WORKSPOT2
 */
public class PercolationStats
{

    private double[] means;
    private int T;

    public PercolationStats(int N, int T) // perform T independent computational experiments on an N-by-N grid
    {
        if (N <= 0 || T <= 0)
        {
            throw new IllegalArgumentException();
        }
        this.T = T;
        means = new double[T];
        for (int i = 0; i < T; i++)
        {
            means[i] = doExperiment(N);
        }
    }

    private double doExperiment(int n)
    {
        Percolation perc = new Percolation(n);
        int randomI, randomJ;
        int total = n * n;
        int opened = 0;
        while (!perc.percolates())
        {
            randomI = StdRandom.uniform(1, n + 1);
            randomJ = StdRandom.uniform(1, n + 1);
            if (!perc.isOpen(randomI, randomJ))
            {
                perc.open(randomI, randomJ);
                opened++;
            }
        }
        return (double) opened / total;
    }

    public double mean()                     // sample mean of percolation threshold
    {
        return StdStats.mean(means);
    }

    public double stddev()                   // sample standard deviation of percolation threshold
    {
        return StdStats.stddev(means);
    }

    public double confidenceLo()             // returns lower bound of the 95% confidence interval{
    {
        double sMean = mean();
        double sDev = stddev();
        return sMean - (1.96d * sDev) / Math.sqrt(T);
    }

    public double confidenceHi()             // returns upper bound of the 95% confidence interval
    {
        double sMean = mean();
        double sDev = stddev();
        return sMean + (1.96d * sDev) / Math.sqrt(T);
    }

    public static void main(String[] args)   // test client, described below     
    {
        int N = Integer.parseInt(args[0]);
        int T = Integer.parseInt(args[1]);
        PercolationStats stats = new PercolationStats(N, T);
        System.out.println("mean                    = " + stats.mean());
        System.out.println("stddev                  = " + stats.stddev());
        System.out.println("95% confidence interval = " + stats.confidenceLo() + ", " + stats.confidenceHi());
    }
}
